package org.apache.cordova.localStorage;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * This class echoes a string called from JavaScript.
 */
public class LocalStorage extends CordovaPlugin {
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("set")) {
            String name = args.getString(0);
            String value = args.getString(1);
            this.set(name, value, callbackContext);
            return true;
        }
        if (action.equals("get")) {
            String name = args.getString(0);
            this.get(name, callbackContext);
            return true;
        }
        return false;
    }

    private void set(final String name, final String value, final CallbackContext callbackContext) {
      cordova.getThreadPool().execute(new Runnable() {
        public void run() {
          if (name != null && name.length() > 0) {
            SharedPreferences ls = cordova.getActivity().getPreferences(Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = ls.edit();
            editor.putString(name, value);
            editor.commit();
            callbackContext.success(0);
          } else {
            callbackContext.error("Expected one non-empty string argument.");
          }
        }
      });

    }

    private void get(final String name, final CallbackContext callbackContext) {
      cordova.getThreadPool().execute(new Runnable() {
        @Override
        public void run() {
          if (name != null && name.length() > 0) {
            Activity activity = cordova.getActivity();
            SharedPreferences ls = activity.getPreferences(Context.MODE_PRIVATE);
            String value = ls.getString(name, "\"\"");
            callbackContext.success(value);
          } else {
            callbackContext.error("Expected one non-empty string argument.");
          }
        }
      });

    }
}
